﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;

namespace Gueei.Gallery.Core.Filters
{
	public class BlurImageFilter:ImageFilter
	{
		private int _blurSize;

		public BlurImageFilter(int blurSize)
		{
			_blurSize = blurSize;
		}

		public override System.Drawing.Image ApplyFilter(System.Drawing.Image image)
		{
			Bitmap blurred = new Bitmap(image.Width, image.Height);
	 
	    // make an exact copy of the bitmap provided
	    using(Graphics graphics = Graphics.FromImage(blurred))
	        graphics.DrawImage(image, new Rectangle(0, 0, image.Width, image.Height),
	            new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);
	 
	    // look at every pixel in the blur rectangle
	    for (Int32 xx = 0; xx < image.Width; xx++)
	    {
	        for (Int32 yy = 0; yy < image.Height; yy++)
	        {
	            Int32 avgR = 0, avgG = 0, avgB = 0;
	            Int32 blurPixelCount = 0;
	 
	            // average the color of the red, green and blue for each pixel in the
	            // blur size while making sure you don't go outside the image bounds
	            for (Int32 x = xx; (x < xx + _blurSize && x < image.Width); x++)
	            {
	                for (Int32 y = yy; (y < yy + _blurSize && y < image.Height); y++)
	                {
	                    Color pixel = blurred.GetPixel(x, y);
	 
	                    avgR += pixel.R;
	                    avgG += pixel.G;
	                    avgB += pixel.B;
	 
	                    blurPixelCount++;
	                }
	            }
	 
	            avgR = avgR / blurPixelCount;
	            avgG = avgG / blurPixelCount;
	            avgB = avgB / blurPixelCount;
	 
	            // now that we know the average for the blur size, set each pixel to that color
	            for (Int32 x = xx; x < xx + _blurSize && x < image.Width && x < image.Width; x++)
	                for (Int32 y = yy; y < yy + _blurSize && y < image.Height && y < image.Height; y++)
	                    blurred.SetPixel(x, y, Color.FromArgb(avgR, avgG, avgB));
	        }
	    }
	 
	    return blurred;
		}
	}
}
